import { DeviceComm } from "../../../devices/MouseDevice";
import { DpiColorConfig } from "../../../types/types.v1.d";
import v1000Config from "../../../config/mouse_info_v1000.json";
import { hexToGrb } from "@/src/utils/colorUtils";

// 添加回调函数类型定义
type DpiProtocolCallbacks = {
  onDpiColorsChange?: (colors: DpiColorConfig) => void;
};

export const dpiValues = v1000Config.dpi.map((item) => item.dpiValue);

export const grbColors = v1000Config.dpi.map((item) => hexToGrb(item.dpiColor));

// 定义颜色配置 (GRB顺序)
export const colorConfig: DpiColorConfig = {
  colors: [
    [
      [0, 255, 0], // 档位1: #ff0000
      [0, 0, 255], // 档位2: #0000ff
      [255, 0, 0], // 档位3: #00ff00
      [255, 255, 0], // 档位4: #ffff00
      [255, 0, 255], // 档位5: #00ffff
      [0, 128, 128], // 档位6: #800080
    ],
    [
      [0, 0, 0],
      [0, 0, 0],
      [0, 0, 0],
      [0, 0, 0],
      [0, 0, 0],
      [0, 0, 0],
    ],
  ],
  // colors: [grbColors],
};

/**
 * DPI协议使用
 */
export class DpiProtocolControl {
  private device: DeviceComm;
  private callbacks: DpiProtocolCallbacks;

  constructor(device: DeviceComm, callbacks: DpiProtocolCallbacks = {}) {
    this.device = device;
    this.callbacks = callbacks;
  }

  /**
   * 更新回调函数
   */
  setCallbacks(callbacks: DpiProtocolCallbacks) {
    this.callbacks = { ...this.callbacks, ...callbacks };
  }

  /**
   * 配置DPI颜色
   */
  async configureDpiColors(): Promise<DpiColorConfig | null> {
    try {
      console.log("设置DPI颜色配置...", colorConfig);
      await this.device.setDpiColors(colorConfig);

      console.log("读取当前DPI颜色配置...");
      const currentColors = await this.device.getDpiColors();
      console.log("当前颜色配置:", currentColors);

      // 触发回调
      if (this.callbacks.onDpiColorsChange) {
        this.callbacks.onDpiColorsChange(currentColors);
      }

      return currentColors;
    } catch (error) {
      console.error("配置DPI颜色失败:", error);
      return null;
    }
  }

  /**
   * 获取当前DPI颜色配置
   */
  async getCurrentDpiColors(): Promise<DpiColorConfig | null> {
    try {
      const colors = await this.device.getDpiColors();
      if (this.callbacks.onDpiColorsChange) {
        this.callbacks.onDpiColorsChange(colors);
      }
      return colors;
    } catch (error) {
      console.error("获取DPI颜色配置失败:", error);
      return null;
    }
  }

  /**
   * 更新DPI颜色配置
   */
  async updateDpiColors(colors: DpiColorConfig): Promise<boolean> {
    try {
      await this.device.setDpiColors(colors);
      const updatedColors = await this.device.getDpiColors();

      if (this.callbacks.onDpiColorsChange) {
        this.callbacks.onDpiColorsChange(updatedColors);
      }

      return true;
    } catch (error) {
      console.error("更新DPI颜色配置失败:", error);
      return false;
    }
  }
}
